package com.example.finance_manager.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.finance_manager.db.SQLiteHelper;
import com.example.finance_manager.models.Payout;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class PayoutDao {
    private SQLiteHelper sqLiteHelper;
    private SQLiteDatabase db;

    public PayoutDao(Context context) {
        sqLiteHelper = new SQLiteHelper(context);
    }

    public long add(Payout payout) {
        db = sqLiteHelper.getWritableDatabase();
        ContentValues cv = getContentView(payout);
        return db.insert("payout", null, cv);
    }

    public void update(Payout payout) {
        Integer id = (Integer) payout.getId();
        db = sqLiteHelper.getWritableDatabase();
        ContentValues cv = getContentView(payout);
        db.update("payout", cv, "id = ?", new String[]{id.toString()});
    }


    public List<Payout> findAll() {
        List<Payout> list = new ArrayList<Payout>();
        db = sqLiteHelper.getReadableDatabase();
        Cursor cursor = db.query("payout", new String[]{"id", "time", "address", "type", "other", "money"}, null, null, null, null, null);
        while (cursor.moveToNext()) {
            Payout payout = new Payout();
            payout.setId(cursor.getInt(0));
            payout.setTime(cursor.getString(1));
            payout.setAddress(cursor.getString(2));
            payout.setType(cursor.getString(3));
            payout.setOther(cursor.getString(4));
            payout.setMoney(cursor.getDouble(5));
            list.add(payout);
        }
        return list;
    }

    public int deleteById(Integer id) {
        db = sqLiteHelper.getWritableDatabase();
        return db.delete("payout", "id = ?", new String[]{id.toString()});
    }


    private ContentValues getContentView(Payout payout) {
        ContentValues cv = new ContentValues();   cv.put("time", payout.getTime());
        cv.put("address", payout.getAddress());
        cv.put("type", payout.getType());
        cv.put("other", payout.getOther());
        cv.put("money", payout.getMoney());
        return cv;
    }
}
